<?php
namespace App\Modules\Relationship\Models;


use App\Http\Services\Message\MessageServices;
use App\Modules\Relationship\Enums\ConstEnum;
use App\Http\Services\CommonServices;
use App\Modules\Relationship\Interfaces\ModelInterface;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Redis;
use App\Http\Model\Base;

class RsRelationshipModel extends Base implements ModelInterface {
    protected $table = "rs_relationship";

    protected $fields = array(
        'id',
        'user_id as userId',
        'friend_id as friendId',
        'type',
        'rs_code as rsCode',
        'intimate'
    );

    public function __construct(array $attributes = [])
    {
        parent::__construct($this->table, $attributes);
        $this->tablePrefix = env('DB_PREFIX');
    }

    // 获取某条用户关系记录
    public function getOneRelation($userId, $friendId){
        $condition = array(
            "user_id"=>$userId,
            "friend_id"=>$friendId,
            "is_deleted"=>0
        );
        $return = $this->getOneByCondition($condition, $this->fields);
        return $return;
    }
    // 获取某条用户关系记录
    public function getRecord(int $userId, int $friendId){
        $condition = array(
            "user_id"=>$userId,
            "friend_id"=>$friendId,
            "is_deleted"=>0
        );

        $return = $this->getOneByCondition($condition, $this->fields);
        return $return;
    }

    // 查询一组记录 不过滤type
    public function getGroupRecordNoType ($userId, $friendId) {
        $re1 = $this->getRecord($userId, $friendId);
        $re2 = $this->getRecord($friendId, $userId);
        if (!$re1 || !$re2) {
            return false;
        }
        return [$re1, $re2];
    }

    // 查询一组记录
    public function getGroupRecord ($userId, $friendId, $type = 1) {
        $re1 = $this->getOneRelationByType($userId, $friendId, $type);
        $re2 = $this->getOneRelationByType($friendId, $userId, $type);
        if (!$re1 || !$re2) {
            return false;
        }
        return [$re1, $re2];
    }

    public function createRecord (array $data){
        return DB::table($this->table)->insertGetId($data);
    }

    public function updateRecord (array $ids, array $data){
        return DB::table($this->table)->whereIn('id', $ids)->update($data);
    }

    public function deleteRecord (array $ids){
        return DB::table($this->table)->whereIn('id',  $ids)->update(array('is_deleted'=>1));
    }


    public function addIntimate (int $id, int $intimate) {
        return DB::table($this->table)->where('id', $id)->increment('intimate', $intimate);
    }

    public function getRecordByUserId (int $userId, $type = 0) {
        $param = array('user_id'=>$userId, 'is_deleted'=>0);
        if ($type != 0) {
            $param['type'] = $type;
        }
        return $this->getOneByCondition($param, $this->fields);
    }
    // 根据不同用户关系查询
    public function getOneRelationByType($userId, $friendId, $type){
        $condition = array(
            "user_id"=>$userId,
            "friend_id"=>$friendId,
            "type"=>$type,
            "is_deleted"=>0
        );

        $return = $this->getOneByCondition($condition, $this->fields);
        return $return;
    }

    // 获取某条用户关系记录
    public function getOneRelationByRsCode($rsCode){
        $condition = array(
            "rs_code"=>$rsCode,
            "is_deleted"=>0
        );

        $return = $this->getListByCondition($condition, $this->fields);
        return $return;
    }

    // 获取好友关系列表
    public function getList ($userId, $offset, $rows, $haveRs = 0):array {
        $table = $this->tablePrefix . $this->table;
        $fields = implode(',', $this->fields);
        $con = "";
        if ($haveRs == 1) {
            $con = " and type = 1";
        }
        $sql = "SELECT {$fields} FROM {$table} WHERE user_id= ? {$con} and is_deleted = 0 ORDER BY type DESC, intimate DESC, id ASC LIMIT ?,?";
        $bindings = array($userId, $offset, $rows);
        $rows = DB::select($sql, $bindings);
        if (!$rows) {
            return array();
        }
        return $rows;
    }

    // 获取好友关系列表
    public function getListCount ($userId, $haveRs = 0):int {
        $table = $this->tablePrefix . $this->table;
        $con = "";
        if ($haveRs == 1) {
            $con = " and type = 1 and intimate >= 1000";
        }
        $sql = "SELECT count(id) as cou FROM {$table} WHERE user_id= ? {$con} and is_deleted = 0";
        $bindings = array($userId);
        $rows = DB::select($sql, $bindings);
        if (!$rows) {
            return 0;
        }
        return $rows[0]->cou;
    }

    // 增长亲密值
//    public function incIntimate ($userId, $friendId, $type, $intimacy) {
//        $row = $this->getOneRelationByType($userId, $friendId, $type);
//        if (!$row) {
//            return false;
//        }
//        $re = DB::table($this->table)
//            ->where('rs_code', $row['rsCode'])
//            ->where("is_deleted", 0)
//            ->increment('intimate', $intimacy);
//        return (bool)$re;
//    }

    // 写入总的用户关系表
    /*
     * data= [userId, friendId, type]
     */
    public function insertIfNoExist ($userId, $friendId, $type):bool
    {
        $re = $this->getRecord($userId, $friendId);// 如果存在关系则是密友 & cp，无需插入rs
        if ($re) {
            return false;
        }
        $record1['user_id'] = $userId;
        $record1['friend_id'] = $friendId;
        $record1['type'] = $type;
        $id1 = DB::table($this->table)->insertGetId($record1);

        $record2['user_id'] = $friendId;
        $record2['friend_id'] = $userId;
        $record2['type'] = $type;
        $id2 = DB::table($this->table)->insertGetId($record2);

        if ($id1 && $id2) {
            $rsCode = $this->getRsCode($userId, $friendId, $id1, $id2);
            DB::table($this->table)->whereIn('id', array($id1, $id2))->update(array('rs_code'=>$rsCode));
        }
        return (bool)$re;
    }

    // 修改数据
    /*
     * data= [userId, friendId, type, intimate]
     */
    public function updateType (array $data):bool {
        $userId = $data['userId'];
        $friendId = $data['friendId'];
        $type = $data['type'];
        $intimacy = $data['intimate'];
        $re1 = $this->getOneRelationByType($userId, $friendId, 1);
        $re2 = $this->getOneRelationByType($friendId, $userId, 1);
        if (!$re1 || !$re2) {
            return false;
        }
        if ($re1['type'] == 1 && !in_array($type, array(2,3))){
            return false;
        }
        $table = $this->tablePrefix . $this->table;
        $sql = "UPDATE {$table} set `type` = {$type},`intimate` = {$intimacy} WHERE id in ({$re1['id']},{$re2['id']})";
        $re = DB::update($sql);
        return (bool)$re;
    }



    /**
     * 删除关系 - 取消关注
     *  ---type 实际删除参数的数值---
     * @param array $data
     * @return bool
     */
    public function deleteRs(array $data){
        $userId = $data['userId'];
        $friendId = $data['friendId'];
        $type = $data['type'];
        $re1 = $this->getRecord($userId, $friendId);
        $re2 = $this->getRecord($friendId, $userId);

        write_log(
            'FriendService'.(isCli()?'-cli':''),
            '[INFO] 取消关注-删除rs-数据',
            [$data,$re1,$re2]
        );

        //$WebHook = config("message.module.modelCp");
        //MessageServices::text($WebHook, '通知-好友关系取消关注-删除rs-uid'.$userId.'-fid:'.$friendId.'-删除type:'.$type.'-当前:'.$re1['type']);

        $table = $this->tablePrefix . $this->table;
        // $sql = "UPDATE {$table} set `is_deleted` = 1,`intimate` = 0 WHERE id in ({$re1['id']},{$re2['id']})";
        //  $sql = 'UPDATE ' . $table . ' set `is_deleted` = 1,`intimate` = 0 WHERE `id` in (' . $re1['id'] .','.$re2['id'] . ') and `type` = ' . $type;
        $sql = 'UPDATE ' . $table . ' set `is_deleted` = 1,`intimate` = 0 WHERE `is_deleted` = 0 and `type` = ' . $type. ' AND ( (`user_id` = '.$userId.' AND `friend_id` = '.$friendId.') OR (`user_id` = '.$friendId.' AND `friend_id` = '.$userId.') )';
        $re = DB::update($sql);

        $table1 = $this->tablePrefix . 'rs_relationship_intimacy_log';
        // $sql1 = "UPDATE {$table1} set `is_deleted` = 1 WHERE rs_code='{$re1['rsCode']}'";
        $sql1 = 'UPDATE ' . $table1 . ' set `is_deleted` = 1 WHERE `rs_code` = "' . $re1['rsCode'] . '" and `type` = ' . $type;
        $re1 = DB::update($sql1);


        return (bool)$re;
    }

    // 生成关系编码
    public function getRsCode ($userId, $friendId, $id1, $id2) : string {
        $code = $id1 . '_' . $id2;
        if ($id1 > $id2) {
            $code = $id2 . '_' . $id1;
        }

        if ($userId > $friendId) {
            $code = $code . '_' . $friendId . '_' . $userId;
        } else {
            $code = $code . '_' . $userId . '_' . $friendId;
        }
        return $code;
    }

    // 增加亲密值
    public function incIntimate($userId, $friendId, $type, $intimate)
    {
        $record = $this->getGroupRecord($userId, $friendId, $type);
        if (!$record) {
            return null;
        }
        $rs1 = DB::table($this->table)->where('id', $record[0]['id'])->increment('intimate', $intimate);
        if (!$rs1) {
            return null;
        }
        $rs2 = DB::table($this->table)->where('id', $record[1]['id'])->increment('intimate', $intimate);
        if (!$rs2) {
            return null;
        }
        $re = $this->getOneRelationByType($userId, $friendId, $type);
        return $re['intimate'];
    }

    public function inesrtone ($data) {
        $id = DB::table($this->table)->insertGetId($data);
        return $id;
    }
    public function updateone ( $id, $data) {
        DB::table($this->table)->where(array('id'=>$id))->update($data);
    }

    public function getAllRecordsByUserId ($userId) {
        $re = DB::table($this->table)
            ->where('user_id',$userId)
            ->where('is_deleted', 0)
            ->select($this->fields)
            ->get();
        return self::objToArray($re);
    }
}

